<template
  ><!---->
  <div id="test">
    <!--<title-top :fnlist="initObj.Fnlist"></title-top>-->
    <table-body :options="initObj"></table-body>
    <hwScoreManage ref="hwScoreManage" :sceneId="curSceneId"></hwScoreManage>
    <checkReportManage
      ref="checkReportManage"
      :sceneId="curSceneId"
      :isDefend="isDefend"
    ></checkReportManage>
    <package-progress
      :show="download.showProgress"
      :progress="download.progress"
      :status="download.progressStatus"
      @change="change"
      title="下载进度"
    ></package-progress>
  </div>
</template>
<script>
import { hwTeamRankStatis, hwDefenseTeamRankStatis } from '@/api/compitionStatic';
import { getTopoTargetList, getDeclareCompanyList } from '@/api/drill_compete';
import { exportAllCompanyReports, exportCompanyReports } from '@/api/referee';
import tableBody from './tableListComponent';
import hwScoreManage from './hwScoreManage.vue';
import checkReportManage from './checkReportManage.vue';
import PackageProgress from '@/components/package-progress/package-progress.vue';
import groupMixin from '@/mixin/groupMixin';
export default {
  name: 'hwTeamRankStatic',
  props: ['sceneId', 'sceneName', 'poll', 'isDefend', 'targetScore','projectId', 'hwExtentionType'],
  components: {
    'table-body': tableBody,
    hwScoreManage,
    checkReportManage,
    PackageProgress
  },
  mixins: [groupMixin],
  data() {
    const d = function(val) {
      this.getRankingStatic(null, null, val);
    }.bind(this);
    return {
      initObj: {
        Button: [
          {
            name: '导出排行',
            fnName: this.exportFile
          },
          {
            name: '导出所有报告及统计信息',
            fnName: this.exportAllCompanyReports
          }
        ],
        Input: [],
        Select: [
          {
            optionsValue: [],
            placeholder: `请选择${this.isDefend ? '单位' : '团队'}`,
            fnName: this.getRankingStaticById
          }
        ],
        DatePicker: {
          isShow: false,
          fnName: d
        },
        Page: {
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        Table: {
          listCol: [
            {
              title:'排行',
              align: 'center',
              key: 'rank',
              placement: 'top-right',
              order: 2,
              render: (h, params) => {
                let ele;
                if (params.row._index < 3 && this.curPage == 1) {
                  ele = h('img', {
                    attrs: {
                      src: require(`../../../../assets/scene/top${params.row._index + 1}.png`)
                    },
                    style: {
                      display: 'inline-block',
                      verticalAlign: 'text-bottom',
                      marginLeft: '20px'
                    }
                  });
                } else {
                  ele = h('span', params.row._index + 1 + (this.curPage - 1) * 10);
                }
                let index = params.row._index + 1;
                let color;
                if (index == 1) {
                  color = '#f34938';
                } else if (index == 2) {
                  color = '#eb8205';
                } else if (index == 3) {
                  color = '#27b666';
                } else {
                  color = '#000';
                }
                return h('span', [
                  h(
                    'span',
                    {
                      style: {
                        color: color
                      }
                    },
                    '排行'
                  ),
                  ele
                ]);
              }
            },
            {
              title: `${this.isDefend ? '单位' : '团队名称'}`,
              key: `${this.isDefend ? 'targetName' : 'teamName'}`,
              align: 'center',
              ellipsis: true,
              tooltip: true,
              placement: 'top-left',
              order: 1,
              width: 240
            },
            {
              title: '总分',
              key: 'totalScore',
              align: 'center',
              ellipsis: true,
              tooltip: true,
              width: 100
            },
            {
              title: '审核通过次数',
              key: 'totalCount',
              align: 'center',
              ellipsis: true,
              sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
              width: 100,
              render: (h, params) => {
                if(params.row.totalCount === 0 || this.hwExtentionType == 2) {
                  return h('P',params.row.totalCount)
                }
                return h(
                  'Tag',
                  {
                    props: {
                      color: 'blue'
                    },
                    style: {
                      cursor: (params.row.totalCount === 0 || this.hwExtentionType == 2) ? '' : 'pointer!important'
                    },
                    nativeOn: {
                      click: () => {
                        if (params.row.totalCount === 0 || this.hwExtentionType == 2) {
                          return;
                        }
                        let query = this.isDefend
                          ? { company: params.row.targetName, groupId: params.row.teamId }
                          : { groupId: params.row.teamId };
                        this.$refs.checkReportManage.openModal(query);
                      }
                    }
                  },
                  params.row.totalCount
                );
              }
            }
          ],
          listData: []
        },
        Fnlist: 'getRankingStatic'
      },
      selName: '',
      timeout: {},
      curPage: 1,
      companyList: [],
      download: {
        progress: 0,
        showProgress: false,
        progressStatus: 'active',
        loading: false
      }
    };
  },
  computed: {
    curSceneId() {
      return this.sceneId || this.$route.query.id;
    }
  },
  watch: {
    teamList(newValue) {
      if (this.isDefend) {
        return;
      }
      this.initObj.Select[0].optionsValue = newValue.filter(
        (item) => item.name !== '目标方管理员组'
      );
    }
  },
  beforeDestroy() {
    clearTimeout(this.timeout);
  },
  created() {
    if(this.hwExtentionType == 2) {
      // 日常渗透-移除导出排行、导出所有报告及统计信息
      this.initObj.Button = []
    }
  },
  mounted() {
    this.getRankingStatic();
    if (this.isDefend) {
      // this.getTopoTargetList(); // 防守方页面需要获取目标列表
      this.getDeclareCompanyList(); // 防守方页面需要获取单位列表
      this.initObj.Table.listCol.push(
        // {
        //   title: '基础分',
        //   key: 'basicScore',
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   width: 100
        // },
        {
          title: '防守得分',
          key: 'defendScore',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100
        },
        {
          title: '被攻击扣分',
          key: 'attackScore',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100
        },
        {
          title: '加减分',
          key: 'exceptScore',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100,
          render: (h, params) => {
            if(this.hwExtentionType == 2) {
              return h('P',params.row.exceptScore)
            }
            return h(
              'Tag',
              {
                props: {
                  color: 'blue'
                },
                style: {
                  cursor: this.hwExtentionType == 2 ? '' : 'pointer!important'
                },
                nativeOn: {
                  click: () => {
                    if(this.hwExtentionType == 2) {
                      return false
                    }
                    this.$refs.hwScoreManage.openModal({ company: params.row.targetName });
                  }
                }
              },
              params.row.exceptScore
            );
          }
        },
      );
      if(this.hwExtentionType != 2) {
        this.initObj.Button.push({
          name: '导出防守方台账',
          fnName: this.exportCompanyReports
        });
        this.initObj.Table.listCol.push({
          title: '操作',
          align: 'center',
          placement: 'top-right',
          key:'action',
          opList:[
            {
              txt:'导出报告及统计信息',
              fun:this.exportCompanyReports
            }
          ]
        }
      );
      }
    } else {
      this.initObj.Table.listCol.push(
        {
          title: '高危数量',
          key: 'highCount',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100
        },
        {
          title: '中危数量',
          key: 'middleCount',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100
        },
        {
          title: '低危数量',
          key: 'lowCount',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100
        },
        {
          title: '加减分',
          key: 'exceptScore',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          sortable: ['hwDrill'].includes(this.$route.query.fromMenu),
          width: 100,
          render: (h, params) => {
            if(this.hwExtentionType == 2) {
              return h('P',params.row.exceptScore)
            }
            return h(
              'Tag',
              {
                props: {
                  color: 'blue'
                },
                style: {
                  cursor: this.hwExtentionType == 2 ? '' : 'pointer!important'
                },
                nativeOn: {
                  click: () => {
                    if(this.hwExtentionType == 2) {
                      return false
                    }
                    this.$refs.hwScoreManage.openModal({ groupId: params.row.teamId });
                  }
                }
              },
              params.row.exceptScore
            );
          }
        }
      );
    }
  },
  methods: {
    // 获取单位列表
    getDeclareCompanyList() {
      let projectId = this.projectId || this.$route.query.prjid;
      getDeclareCompanyList(projectId)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.companyList = data.map((item) => {
              return {
                id: item,
                name: item
              };
            });
            this.initObj.Select[0].optionsValue = this.companyList;
          } else {
            this.$Message.warning(message);
          }
        })
        .catch((error) => {});
    },
    // 获取目标列表
    // getTopoTargetList() {
    //   getTopoTargetList({
    //     pageIndex: 1,
    //     pageSize: 2147483646,
    //     projectId: this.$route.query.prjid
    //   })
    //     .then(({ code, message, data = {} }) => {
    //       if (code !== 1) {
    //         this.$Message.warning(message);
    //       } else {
    //         this.targetList = (data.items || []).map((item) => {
    //           // item.name = item.company;
    //           return item;
    //         });
    //         this.initObj.Select[0].optionsValue = this.targetList;
    //       }
    //     })
    //     .catch(() => {
    //       this.$Message.error('获取目标列表异常');
    //     });
    // },
    getRankingStaticById(id) {
      this.selName = this.isDefend ? id : this.getTeamNameById(id);
      this.getRankingStatic();
    },
    getTargetName(id) {
      return (this.targetList.find((item) => item.id === id) || {}).name;
    },
    getRankingStatic(page, pageSize, querytime) {
      let _this = this;
      let pages = page || 1;
      this.$set(this.initObj.Page, 'currentPage', pages);
      let rows = pageSize || _this.PZ || 10;
      let id = '';
      let params = {
        pageIndex: pages,
        pageSize: rows
      };
      this.curPage = pages;
      if (this.selName) {
        this.isDefend ? (params.targetName = this.selName) : (params.teamName = this.selName);
      }
      let sceneId = this.sceneId || _this.$route.query.id;
      if (sceneId) {
        let api = this.isDefend ? hwDefenseTeamRankStatis : hwTeamRankStatis;
        api(sceneId, params).then((data) => {
          if (data.code == 1) {
            _this.initObj.Table.listData = this.isDefend
              ? data.data.items.map((item) => {
                  item.targetScore = this.targetScore;
                  return item;
                })
              : data.data.items;
            _this.initObj.Page.total = data.data.total;
            if (this.poll) {
              //如果需要轮询
              clearTimeout(this.timeout);
              this.timeout = setTimeout(() => {
                this.getRankingStatic(page, pageSize);
              }, 3000);
            }
          }
        });
      }
    },
    exportFile() {
      let sceneId = this.sceneId || this.$route.query.id;
      let sceneName = this.sceneName || this.$route.query.name;
      let href = this.isDefend
        ? `/api/compete/teamScoreRecord/exportDe/${sceneId}/${sceneName}`
        : `/api/compete/teamScoreRecord/exportAt/${sceneId}/${sceneName}`;
      let a = document.createElement('a');
      document.body.appendChild(a);
      a.href = href;
      a.download = ''; //命名下载名称
      a.click(); //点击触发下载
      a.remove();
    },
    exportCompanyReport(data) {
      let sceneId = this.sceneId || this.$route.query.id;
      let sceneName = this.sceneName || this.$route.query.name;
      let href = `/api/compete/scoring/newDownloadZip/${sceneId}/${sceneName}?company=${data.targetName}`;
      console.log(href);
      let a = document.createElement('a');
      document.body.appendChild(a);
      a.href = href;
      a.download = ''; //命名下载名称
      a.click(); //点击触发下载
      a.remove();
    },
    //导出任务下的所有报告
    exportCompanyReports(data) {
      let sceneId = this.sceneId || this.$route.query.id;
      let sceneName = this.sceneName || this.$route.query.name;
      let company = data ? data.targetName : '';
      this.download.loading = true;
      this.download.showProgress = true;
      exportCompanyReports(sceneId, sceneName, company ? { company } : {}, this.downFileProgress)
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = company
              ? `${sceneName}-${company}-报告及统计信息.zip`
              : `${sceneName}-防守方台账.zip`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('报告下载成功');
          } else {
            this.$Message.warning('下载失败，不存在文件数据');
          }
          this.download.loading = false;
        })
        .catch((error) => {
          this.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.download.loading = false;
        })
        .finally(() => {
          this.download.progress = 100;
          setTimeout(() => {
            this.download.showProgress = false;
            this.download.progressStatus = 'active';
            this.download.progress = 0;
          }, 2000);
        });
    },
    //导出任务下的所有报告
    exportAllCompanyReports(data) {
      let sceneId = this.sceneId || this.$route.query.id;
      let sceneName = this.sceneName || this.$route.query.name;
      this.download.loading = true;
      // this.download.showProgress = true;
      exportAllCompanyReports(sceneId, sceneName, this.isDefend ? 2 : 1) //this.downFileProgress
        .then((res) => {
          let { code, message } = res.data;
          if (code == 1) {
            this.$Message.info({
              content: message,
              duration: 5,
              closable: true
            });
          } else {
            this.$Message.error(message);
          }
          return;
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${sceneName}-${
              this.isDefend ? '防守方' : '攻击方'
            }-所有报告及统计信息.zip`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('报告下载成功');
          } else {
            this.$Message.warning('下载失败，不存在文件数据');
          }
          this.download.loading = false;
        })
        .catch((error) => {
          // this.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.download.loading = false;
        })
        .finally(() => {
          this.download.progress = 100;
          setTimeout(() => {
            this.download.showProgress = false;
            this.download.progressStatus = 'active';
            this.download.progress = 0;
          }, 2000);
        });
    },
    downFileProgress(progress) {
      let currentProgress = progress.loaded * 1; //B单位
      if (this.total) {
        this.total += currentProgress;
      } else {
        this.total = currentProgress;
      }
      currentProgress = this.total - currentProgress ? currentProgress : currentProgress / 2;
      let rate = (((this.total - currentProgress) / this.total) * 100).toFixed(2) * 1;
      if (!this.rate || rate > this.rate) {
        this.download.progress = rate;
      }
    },
    change(val) {
      this.showProgress = val;
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}
.targetHeader {
  padding: 10px;
  margin-bottom: 10px;
}
</style>
